# aarch64 x86_64
OS_ARCH="x86_64"
# Pull the image 
DOCKER_HUB='hub.oepkgs.net'
DOCKER_HUB_TAG_PREFIX="${DOCKER_HUB}/a-ops"

arangodb_tag="latest"
ARANGODB_PORT=8529

#=======Common Utils========#
function echo_err_exit() {
    echo -e "\e[31m $@ \e[0m"
    exit 1;
}
function docker_pull_image() {
    tag_name="$1"

    if ! docker --version >/dev/null 2>&1 ; then
         echo_warn "Docker cmd not found, try installing docker firstly"
         yum install docker -y
         [ $? -ne 0 ] && echo_err_exit "Error: fail to install docker"
    fi

    docker pull ${DOCKER_HUB_TAG_PREFIX}/"${tag_name}" 2>gopher_deploy_err.log
    if [ $? -ne 0 ] ; then
        if cat gopher_deploy_err.log | grep -q "unknown authority" ; then
            echo_warn "Add hub.oepgs.net to insecure-registries in /etc/docker/daemon.json and restart docker, then retry deploying"
        fi
        rm -rf gopher_deploy_err.log
        echo_err_exit "Error: failed to pull docker image: ${DOCKER_HUB_TAG_PREFIX}/${tag_name}"
    else
        rm -rf gopher_deploy_err.log
    fi
}

# Start the container 
function deploy_arangodb() {
    container_name="gala-arangodb"
    if [ $(getconf PAGE_SIZE) -gt 4096 ] ; then
        echo_err_exit "Arangodb not supported on systems whose PAGE SIZE larger than 4096"
    fi

    if docker inspect ${container_name} >/dev/null 2>&1 ; then
        echo -e "arangodb container has already been created, running"
        docker start ${container_name} || echo_err_exit "Error: fail to run arangodb container"
        return
    fi

    echo -e "Pulling/Loading arangodb docker images"
    arangodb_tag="arangodb-${OS_ARCH}"
    # docker_pull_image "${arangodb_tag}"
    
    echo -e "Creating and running arangodb container"
    docker run -d --name ${container_name} -p $ARANGODB_PORT:$ARANGODB_PORT -e ARANGO_NO_AUTH=yes ${DOCKER_HUB_TAG_PREFIX}/${arangodb_tag}
    [ $? -ne 0 ] && echo_err_exit "Error: fail to run arangodb container"
}
deploy_arangodb
